package com.nbstar.film.spider.http;

import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.net.HttpURLConnection;
import java.util.zip.GZIPInputStream;

@Slf4j
public class StringParser implements HttpResultParserAdaper {

    @Override
    public String parseResult(HttpURLConnection conn) throws IOException {
        //StringBuilder result = new StringBuilder();

        InputStream ips = null;
        // 取前两个字节
        byte[] header = new byte[2];

        synchronized (this) {
            if (conn.getResponseCode() != 200) {
                log.error("{} return code:{}", conn.getURL(), conn.getResponseCode());
                return "";
            }
        }

        BufferedInputStream bis = new BufferedInputStream(conn.getInputStream());
        bis.mark(2);
        int result = bis.read(header);
        // reset输入流到开始位置
        bis.reset();
        // 判断是否是GZIP格式
        int ss = (header[0] & 0xff) | ((header[1] & 0xff) << 8);
        if(result!=-1 && ss == GZIPInputStream.GZIP_MAGIC) {
            //System.out.println("为数据压缩格式...");
            ips= new GZIPInputStream(bis);
        } else {
            // 取前两个字节
            ips= bis;
        }



        StringBuilder sb = new StringBuilder();
        //InputStream stream = conn.getInputStream();
        BufferedReader reader = new BufferedReader(new InputStreamReader(ips,"utf-8"));
        String line = "";
        while ((line = reader.readLine()) != null){
            sb.append(line + "\r\n");
        }

        ips.close();
        return sb.toString();
    }
}
